﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<新建接口帐号>
-- =============================================
CREATE PROCEDURE [dbo].[proc_AB_Interface_Create](
	@CompanyId INT,
	@CompanName NVARCHAR(50),
	@ProductId VARCHAR(200),
	@ProductName NVARCHAR(50),
	@syzh INT
)

AS
BEGIN
	DECLARE @New_ProductId VARCHAR(200)
	SET @New_ProductId=''
	
	DECLARE @SourceSql   varchar(8000),@StrSeprate   varchar(100)
	SET @SourceSql=@ProductId+','
	SET @StrSeprate=','
	DECLARE @ch varchar(100)
	DECLARE @PName NVARCHAR(300)
	SET @PName=''
	WHILE(@SourceSql<>'')   
		BEGIN   
			set   @ch=left(@SourceSql,charindex(',',@SourceSql,1)-1)   
			--SELECT  @ch 
			--判断该公司的所有接口帐号是否已经添加过该产品
			IF (SELECT COUNT(0) FROM AB_Interface WHERE ProductId LIKE '%{'+@ch+'}%' AND CompanyId=@CompanyId AND syzh=0)>0 
				BEGIN 
					--SET @PName=@PName+','+(SELECT Title FROM Product WHERE id=@ch)
					SELECT Title FROM Product WHERE id=@ch
					RETURN
				END
			ELSE 
				BEGIN --如果不重复 将原有产品ID和当前不重复的ID组合成新的字符串
					SET @New_ProductId=@New_ProductId+'{'+@ch+'}'
				END
			set   @SourceSql=stuff(@SourceSql,1,charindex(',',@SourceSql,1),'')  
		END 
		
		
		IF LEN(@PName)>0
			BEGIN
				SELECT @PName
			END
		ELSE
			BEGIN
				-- 创建接口帐号
				INSERT INTO [AB_Interface]
				   ([CompanyId]
				   ,[Companyname]
				   ,[ProductId]
				   ,[Productname]
				   ,[syzh])
				VALUES
				   (
					@CompanyId
					,@CompanName
					,@New_ProductId --带{}的ID
					,@ProductName
					,@syzh
				   )
				SELECT 1
			END
END
